//
//  KYZXVideoCollectionVC.m
//  KuYouZiXun
//
//  Created by lanou on 15/8/10.
//  Copyright (c) 2015年 lanou. All rights reserved.
//

#define kURL @"http://appapi.gamersky.com/v1/videocontentlist"

#import "KYZXVideoCollectionVC.h"

#import "LJRequestManagerBlock.h"

#import "KYZXVideoListModel.h"

#import "KYZXVideoCollectionViewCell.h"

#import "KYZXUserInfo.h"

#import "MJRefresh.h"
typedef NS_ENUM(NSInteger, RefreshType) {
    RefreshNew,
    RefreshMore,
    RefreshError//没有网的时候
};
@interface KYZXVideoCollectionVC ()

{
    RefreshType _refreshType;
}
@end

@implementation KYZXVideoCollectionVC

static NSString * const reuseIdentifier = @"Cell";


- (void)addRefreshNew
{
    // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
    self.collectionView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _refreshType = RefreshNew;
        [self.parameterDic setValue:@"1" forKey:@"pageIndex"];
        [self requestData:self.parameterDic];
    }];
    // 马上进入刷新状态
    [self.collectionView.header beginRefreshing];
}

- (void)addRefreshMore
{
    // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
    self.collectionView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _refreshType = RefreshMore;
        NSString *page = [self.parameterDic valueForKey:@"pageIndex"];
        NSInteger pageNew = [page integerValue] + 1;
        
        [self.parameterDic setValue:[NSString stringWithFormat:@"%d",pageNew] forKey:@"pageIndex"];
        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:self.parameterDic];
        [self requestData:dic];
    }];
}

- (void)endRefreshing{
    
    if (_refreshType == RefreshNew) {
        [self.collectionView.header endRefreshing];
        [self addRefreshMore];
    }
    if (_refreshType == RefreshMore) {
        [self.collectionView.footer endRefreshing];
    }
    
}




- (void)dealloc{
    
    [[KYZXUserInfo standardKYZXUserInfo] removeObserver:self];
}

- (NSMutableArray *)dataSource{

    if (_dataSource == nil) {
        _dataSource = [[NSMutableArray alloc] initWithCapacity:0];
    }
    return _dataSource;
}


- (NSDictionary *)parameterDic{

    if (_parameterDic == nil) {
        _parameterDic = [@{@"nodes":[self.nodeModel.nodeId stringValue], @"specials":@"" ,@"pageIndex":@"1",@"pageCount":@"20",@"tag":@""} mutableCopy];
    }
    return _parameterDic;
}

#pragma mark 获取数据

- (void)requestData:(NSDictionary *)dic{

    [LJRequestManagerBlock manager:POST requestWith:kURL dic:dic finish:^(NSData *data) {
        [self parseData:data];
    } error:^(NSError *error) {
        
    }];
}


//解析数据
- (void)parseData:(NSData *)data
{
    //程序第一次尽量的时候没有网,数据库里面也没有数据 所以会蹦,我们判断一下如果data为nil 直接返回
    if (data == nil) {
        //        NSLog(@"即没有网 数据库也没有数据");
        [self endRefreshing];
        return;
    }
    if (_refreshType == RefreshNew) {
        self.dataSource = nil;
    }
    NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves error:nil];
    NSArray *resultArray = dataDict[@"result"];
    for (NSDictionary *dic in resultArray) {
        KYZXVideoListModel *model = [[KYZXVideoListModel alloc] init];
        [model setValuesForKeysWithDictionary:dic];
        [self.dataSource addObject:model];
    }
    [self endRefreshing];
    [self.collectionView reloadData];
}

- (void)viewDidLoad {
    
    [super viewDidLoad];
    [self.collectionView registerNib:[UINib nibWithNibName:@"KYZXVideoCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:reuseIdentifier];
    self.collectionView.backgroundColor = [KYZXUserInfo standardKYZXUserInfo].backgroundColor;
    [self addRefreshNew];
    [[KYZXUserInfo standardKYZXUserInfo]addObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
   
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark <UICollectionViewDataSource>

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {

    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {

    return [self.dataSource count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    KYZXVideoListModel *model = self.dataSource[indexPath.item];
    KYZXVideoCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    cell.model = model;
    return cell;
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{

    self.collectionView.backgroundColor = [KYZXUserInfo standardKYZXUserInfo].backgroundColor;
}

@end
